package com.systop.asset.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.systop.asset.entity.DeptUser;
import com.systop.asset.mapper.DeptUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.systop.asset.mapper.DepartmentMapper;
import com.systop.asset.entity.Department;
import com.systop.asset.service.IDepartmentService;

/**
 * 组织架构部门信息Service业务层处理
 * 
 * @author lsp
 * @date 2025-06-26
 */
@Service
public class DepartmentServiceImpl implements IDepartmentService 
{
    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private DeptUserMapper deptUserMapper;

    /**
     * 根据部门ID递归获取所属公司名称
     *
     * @param deptId 部门ID
     * @param count 递归计数器，用于防止无限递归 必须传参为0
     * @return 公司名称字符串（顶级部门名称），如果部门不存在返回空字符串，如果递归过深返回"组织结构有误"
     */
    @Override
    public String  getCompanyNameByDeptId(Long deptId, int count) {
        // 1. 根据部门ID从数据库查询部门信息
        Department department = departmentMapper.selectDepartmentById(deptId);

        // 检查递归深度，防止循环引用导致的无限递归
        if (count == 200) {
            return "组织结构有误";
        }

        // 处理查询到的部门信息
        if (department != null) {
            // 2. 判断当前部门是否为顶级部门（parentId=0）
            if (department.getParentId() == 0) {
                // 3. 如果是顶级部门，直接返回部门名称（即公司名称）
                return department.getDeptName();
            } else {
                // 4. 如果不是顶级部门，递归查询父部门
                // 递增计数器并继续向上查找
                return getCompanyNameByDeptId(department.getParentId(), ++count);
            }
        } else {
            // 5. 部门不存在时返回空字符串
            return "";
        }
    }
    /**
     * 查询组织架构部门信息
     * 
     * @param id 组织架构部门信息主键
     * @return 组织架构部门信息
     */
    @Override
    public Department selectDepartmentById(Long id)
    {
        return departmentMapper.selectDepartmentById(id);
    }

    /**
     * 查询组织架构部门信息列表
     * 
     * @param department 组织架构部门信息
     * @return 组织架构部门信息
     */
    @Override
    public List<Department> selectDepartmentList(Department department)
    {
        return departmentMapper.selectDepartmentList(department);
    }


    /**
     * 查询组织架构部门信息列表
     *
     * @param department 组织架构部门信息
     * @return 组织架构部门信息
     */
    @Override
    public List<Department> selectDepartmentTree(Department department)
    {
        return buildTree(departmentMapper.selectDepartmentList(department));
    }

    /**
     *
     * 新增组织架构部门信息
     * 
     * @param department 组织架构部门信息
     * @return 结果
     */
    @Override
    public int insertDepartment(Department department)
    {

        int ret =  departmentMapper.insertDepartment(department);
        if (department.getManagerId() != null && department.getManagerId() > 0) {
//            deptUserMapper.deleteDeptUserByDeptId(department.getId());
            DeptUser deptUser = new DeptUser();
            deptUser.setDeptId(department.getId());
            deptUser.setUserId(department.getManagerId());
            deptUserMapper.insertDeptUser(deptUser);
        }
        return ret;
    }

    /**
     * 修改组织架构部门信息
     * 
     * @param department 组织架构部门信息
     * @return 结果
     */
    @Override
    public int updateDepartment(Department department)
    {
        if (department.getManagerId() != null && department.getManagerId() > 0) {
            deptUserMapper.deleteDeptUserByDeptId(department.getId());
            DeptUser deptUser = new DeptUser();
            deptUser.setDeptId(department.getId());
            deptUser.setUserId(department.getManagerId());
            deptUserMapper.insertDeptUser(deptUser);
        }
        return departmentMapper.updateDepartment(department);
    }

    /**
     * 批量删除组织架构部门信息
     * 
     * @param ids 需要删除的组织架构部门信息主键
     * @return 结果
     */
    @Override
    public int deleteDepartmentByIds(Long[] ids)
    {
        return departmentMapper.deleteDepartmentByIds(ids);
    }

    /**
     * 删除组织架构部门信息信息
     * 
     * @param id 组织架构部门信息主键
     * @return 结果
     */
    @Override
    public int deleteDepartmentById(Long id)
    {
        return departmentMapper.deleteDepartmentById(id);
    }



    /**
     * 将部门列表转换为树状结构
     * @param departments 部门列表
     * @return 树状结构的部门列表(顶级部门)
     */
    public static List<Department> buildTree(List<Department> departments) {
        // 用于存储所有部门的映射表(id -> department)
        Map<Long, Department> departmentMap = new HashMap<>();

        // 存储顶级部门(没有父部门或父部门不存在的部门)
        List<Department> roots = new ArrayList<>();

        // 第一次遍历: 将所有部门存入映射表
        for (Department dept : departments) {
            departmentMap.put(dept.getId(), dept);
        }

        // 第二次遍历: 建立父子关系
        for (Department dept : departments) {
            Long parentId = dept.getParentId();

            if (parentId == null || parentId == 0) {
                // 如果没有父ID或父ID为0，认为是顶级部门
                roots.add(dept);
            } else {
                // 查找父部门
                Department parent = departmentMap.get(parentId);
                if (parent != null) {
                    // 如果找到父部门，将当前部门添加到父部门的子列表中
                    parent.addChild(dept);
                } else {
                    // 如果找不到父部门，也作为顶级部门处理
                    roots.add(dept);
                }
            }
        }

        return roots;
    }
}
